package org.hanbo.code.repository.action;

import org.hanbo.code.repository.persistence.entity.RegisteredUser;
import org.hanbo.code.repository.persistence.entity.RegisteredUserDAO;

import com.google.appengine.api.datastore.Key;

public class UserRegistrationAction  extends GaeActionSupportBase
{
	private static final long serialVersionUID = -6657233047991007955L;
	
	private boolean userAgreedToTerm;
		
	public void validate()
	{
		if (userAgreedToTerm == false)
		{
			addFieldError("agreeToTerm", "You must agree to User Agreement by checking the check box");
		}
	}
	
	public String execute()
	{
		if (!super.checkLogin())
		{
			return super.getCurrentStageValue();
		}
				
		if (this.userAgreedToTerm)
		{
			String userEmail = super.getLoggedInUser().getEmail();
			String userNickName = super.getLoggedInUser().getNickname();
			
			//System.out.println("Registering " + userEmail);
			
			RegisteredUser regUser = new RegisteredUser();
			regUser.setUserName(userEmail);
			regUser.setUserDisplayName(userNickName);
			regUser.setUserActiveStatus(true);
			
			RegisteredUserDAO regUserDAO = new RegisteredUserDAO();
			regUserDAO.acquirePersistenceManager();
			Key newUserId = regUserDAO.persistRegisteredUser(regUser);
//			if(newUserId != null)
//			{
//				System.out.println("Registered user id: " + newUserId.getId());
//			}
			regUserDAO.releasePersistenceManager();
			
			regUserDAO.acquirePersistenceManager();
			RegisteredUser regUserTest = regUserDAO.getRegisteredUserById(newUserId);
			//System.out.println("Newly Registered user queried: " + regUserTest.getUserName());
			@SuppressWarnings("unused")
			RegisteredUser regUserTest2 = regUserDAO.getRegisteredUserByEmail(regUserTest.getUserName());
			//System.out.println("Newly Registered user queried: " + regUserTest2.getUserDisplayName());
			regUserDAO.releasePersistenceManager();

			System.out.println("Registered successfully");
			return SUCCESS;
		}
		
		return INPUT;
	}
	
    public String getRedirectLogin()
    {
    	return GaeActionSupportBase.createLogInLink("../SaveUserRegistration");
    }
    
    public String getCurrentUserName()
    {
    	return super.getLoggedInUser().getNickname();
    }

    public String getLogoutUrl()
    {
    	return GaeActionSupportBase.createLogOutLink("../SaveUserRegistration");
    }
	
	public void setAgreeToTerm(boolean value)
	{
		userAgreedToTerm = value;
	}
	
	public boolean getAgreeToTerm()
	{
		return userAgreedToTerm;
	}
	
	public String getNextActionPage()
	{
		return "/index.action";
	}

	public String getRedirectDisplayMessage()
	{
		String userNickName = super.getLoggedInUser().getNickname();
		return "Registration completed, " + userNickName + ". Thank you.";
	}
}
